package com.atguigu.java2;

import com.atguigu.java1.Person;
import org.junit.Test;

import java.lang.annotation.Annotation;
import java.lang.reflect.Modifier;
import java.util.stream.Stream;

/**
 * @author : leimingchao
 * @Description: 获取运行时类的方法结构
 * @date Date : 2021年06月13日 17:46
 */
public class MethodTest {

    @Test
    public void test() {
        Class clazz = Person.class;
        //getMethods():获取当前运行时类及其所有父类中声明为public权限的方法
        Stream.of(clazz.getMethods()).forEach(System.out::println);
        System.out.println("=======================================");
        //getDeclaredMethods():获取当前运行时类中所有方法,不包含父类中声明的方法
        Stream.of(clazz.getDeclaredMethods()).forEach(System.out::println);
    }

    /**
     * @Xxxx 权限修饰符  返回值类型   方法名(参数类型1 形参名,.......) throws XxxxException{}
     */
    @Test
    public void test2() {
        //1.获取方法声明的注解
        Class clazz = Person.class;
        Stream.of(clazz.getDeclaredMethods()).forEach(item -> {
            Annotation[] annotations = item.getAnnotations();
            Stream.of(annotations).forEach(annotation -> {
                System.out.println(annotation);
            });

            //2.获取权限修饰符
            System.out.print(Modifier.toString(item.getModifiers()) + "\t");


            //3.获取返回值类型
            Class returnType = item.getReturnType();
            System.out.print(returnType.getName() + "\t");

            //4.获取方法名
            System.out.print(item.getName());

            System.out.print("(");
            //5.形参列表
            Class[] parameterTypes = item.getParameterTypes();

            if (!(parameterTypes == null && parameterTypes.length == 0)) {
                for (int i = 0; i < parameterTypes.length; i++) {
                    if (i == parameterTypes.length - 1) {
                        System.out.print(parameterTypes[i].getName() + " args_" + i);
                        break;
                    }
                    System.out.print(parameterTypes[i].getName() + " args_" + i + ",");
                }
            }

            System.out.print(")");

            //6.抛出的异常
            Class[] exceptionTypes = item.getExceptionTypes();
            if (exceptionTypes.length > 0) {
                System.out.print(" throws ");
                for (int i = 0; i < exceptionTypes.length; i++) {
                    if (i == exceptionTypes.length - 1) {
                        System.out.print(exceptionTypes[i].getName());
                        break;
                    }
                    System.out.print(exceptionTypes[i].getName() + ",");
                }
            }

            System.out.println();
        });
    }
}
